package cn.dsscm.controller;

import cn.dsscm.pojo.Role;
import cn.dsscm.pojo.User;
import cn.dsscm.service.RoleService;
import cn.dsscm.service.UserService;
import cn.dsscm.tools.Constants;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageInfo;
import com.mysql.cj.util.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/sys/user")
public class UserController {
    private final Logger logger = Logger.getLogger(UserController.class);

    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;

    @RequestMapping(value = "/list.html")
    public String getUserList(
            Model model,
            @RequestParam(value = "queryname", required = false) String queryUserName,
            @RequestParam(value = "queryUserRole", required = false) Integer queryUserRole,
            @RequestParam(value = "pageIndex", required = false) Integer pageIndex) {
        logger.info("getUserList ---- > queryUserName: " + queryUserName);
        logger.info("getUserList ---- > queryUserRole: " + queryUserRole);
        logger.info("getUserList ---- > pageIndex: " + pageIndex);
        PageInfo<User> upi = null;
        List<Role> roleList = null;
        // 设置页面容量
        int pageSize = Constants.pageSize;
        // 页码为空默认分第一页
        if (null == pageIndex) {
            pageIndex = 1;
        }
        if (queryUserName == null) {
            queryUserName = "";
        }
        try {
            upi = userService.getUserList(queryUserName, queryUserRole,
                    pageIndex, pageSize);
            roleList = roleService.getRoleList();
        } catch (Exception e) {
            e.printStackTrace();
        }

        model.addAttribute("pi", upi);
        model.addAttribute("roleList", roleList);
        model.addAttribute("queryUserName", queryUserName);
        model.addAttribute("queryUserRole", queryUserRole);
        return "userlist";
    }

    @RequestMapping(value = "/add.html", method = RequestMethod.GET)
    public String addUser(Model model) {
        List<Role> roleList = null;
        try {
            roleList = roleService.getRoleList();
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("roleList", roleList);
        return "useradd";
    }

    @RequestMapping(value = "/addsave.html", method = RequestMethod.POST)
    public String addUserSave(User user,
                              HttpSession session,
                              HttpServletRequest request) {
        System.out.println("--------------进入添加用户方法---------");
        user.setCreatedBy(((User) session.getAttribute(Constants.USER_SESSION)).getId());
        user.setCreationDate(new Date());
        try {
            if (userService.add(user)) {
                return "redirect:/sys/user/list.html";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "useradd";
    }

    @RequestMapping(value = "/modify/{id}", method = RequestMethod.GET)
    public String getUserById(@PathVariable String id, Model model,
                              HttpServletRequest request) {
        User user = new User();
        try {
            user = userService.getUserById(Integer.parseInt(id));
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute(user);
        return "usermodify";
    }

    @RequestMapping(value = "/modifysave.html", method = RequestMethod.POST)
    public String modifyUserSave(
            User user,
            HttpSession session,
            HttpServletRequest request) {
        System.out.println(user);
        logger.debug("modifyUserSave id===================== " + user.getId());
        user.setModifyBy(((User) session
                .getAttribute(Constants.USER_SESSION)).getId());
        user.setModifyDate(new Date());
        try {
            if (userService.modify(user)) {
                return "redirect:/sys/user/list.html";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "usermodify";
    }

    @RequestMapping(value = "/ucexist.json")
    @ResponseBody
    public Object userCodeIsExit(@RequestParam String userCode) {
        logger.debug("userCodeIsExit userCode===================== " + userCode);
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if (StringUtils.isNullOrEmpty(userCode)) {
            resultMap.put("userCode", "exist");
        } else {
            User user = null;
            try {
                user = userService.selectUserCodeExist(userCode);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (null != user)
                resultMap.put("userCode", "exist");
            else
                resultMap.put("userCode", "noexist");
        }
        return JSONArray.toJSONString(resultMap);
    }

    @RequestMapping(value = "/rolelist.json", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public Object getRoleList() {
        List<Role> roleList = null;
        try {
            roleList = roleService.getRoleList();
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.debug("roleList size: " + roleList.size());
        return JSONArray.toJSONString(roleList);
    }

    @RequestMapping(value = "/deluser.json", method = RequestMethod.GET)
    @ResponseBody
    public Object deluser(@RequestParam String id) {
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if (StringUtils.isNullOrEmpty(id)) {
            resultMap.put("delResult", "notexist");
        } else {
            try {
                if (userService.deleteUserById(Integer.parseInt(id)))
                    resultMap.put("delResult", "true");
                else
                    resultMap.put("delResult", "false");
            } catch (NumberFormatException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return JSONArray.toJSONString(resultMap);
    }

    @RequestMapping(value = "/view/{id}", method = RequestMethod.GET)
    public String view(@PathVariable String id, Model model,
                       HttpServletRequest request) {
        logger.debug("view id===================== " + id);
        User user = new User();
        try {
            user = userService.getUserById(Integer.parseInt(id));
            if (user.getImgPath() != null && !"".equals(user.getImgPath())) {
                String[] paths = user.getImgPath().split("/" + File.separator);
                logger.debug("view picPath paths[paths.length-1]============ "+ paths[paths.length - 1]);
                user.setImgPath(request.getContextPath()
                        + "/statics/uploadfiles/" + paths[paths.length - 1]);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute(user);
        return "userview";
    }

    @RequestMapping(value = "/pwdmodify.html", method = RequestMethod.GET)
    public String pwdModify(HttpSession session) {
        if (session.getAttribute(Constants.USER_SESSION) == null) {
            return "redirect:/user/login.html";
        }
        return "pwdmodify";
    }

    @RequestMapping(value = "/pwdmodify.json", method = RequestMethod.POST)
    @ResponseBody
    public Object getPwdByUserId(@RequestParam String oldpassword,
                                 HttpSession session) {
        logger.debug("getPwdByUserId oldpassword ===================== "
                + oldpassword);
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if (null == session.getAttribute(Constants.USER_SESSION)) {// session过期
            resultMap.put("result", "sessionerror");
        } else if (StringUtils.isNullOrEmpty(oldpassword)) {// 旧密码输入为空
            resultMap.put("result", "error");
        } else {
            String sessionPwd = ((User) session
                    .getAttribute(Constants.USER_SESSION)).getUserPassword();
            if (oldpassword.equals(sessionPwd)) {
                resultMap.put("result", "true");
            } else {// 旧密码输入不正确
                resultMap.put("result", "false");
            }
        }
        return JSONArray.toJSONString(resultMap);
    }

    @RequestMapping(value = "/pwdsave.html")
    public String pwdSave(
            @RequestParam(value = "newpassword") String newPassword,
            HttpSession session, HttpServletRequest request) {
        boolean flag = false;
        Object o = session.getAttribute(Constants.USER_SESSION);
        if (o != null && !StringUtils.isNullOrEmpty(newPassword)) {
            try {
                flag = userService.updatePwd(((User) o).getId(), newPassword);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (flag) {
                request.setAttribute(Constants.SYS_MESSAGE,
                        "修改密码成功,请退出并使用新密码重新登录！");
                session.removeAttribute(Constants.USER_SESSION);// session注销
                return "login";
            } else {
                request.setAttribute(Constants.SYS_MESSAGE, "修改密码失败！");
            }
        } else {
            request.setAttribute(Constants.SYS_MESSAGE, "修改密码失败！");
        }
        return "pwdmodify";
    }

}
